#ifndef DictUtil_h__
#define DictUtil_h__

#include "../infLib/infLib.h"
#include "FileSystem.h"

INF_INLINE void WriteString( const char *s, File *f ) {
    int	len = inf::Str::length( s );
    if ( len >= INF_MAX_STRING_CHARS-1 ) {
        inf::error( "Dict::WriteToFileHandle: bad string" );
    }
    f->Write( s, inf::Str::length( s ) + 1 );
}

INF_INLINE inf::Str ReadString( File *f ) {
    char	str[INF_MAX_STRING_CHARS];
    int		len;

    for ( len = 0; len < INF_MAX_STRING_CHARS; len++ ) {
        f->Read( (void *)&str[len], 1 );
        if ( str[len] == 0 ) {
            break;
        }
    }
    if ( len == INF_MAX_STRING_CHARS ) {
        inf::error( "Dict::ReadFromFileHandle: bad string" );
    }

    return inf::Str( str );
}

INF_INLINE void WriteToFileHandle( File *f, const inf::Dict& dict ) {
    int c = inf::little_long( dict.get_num_keyvalues() );
    const inf::KeyValue* keyValue = NULL;
    f->Write( &c, sizeof( c ) );
    for ( int i = 0; i < dict.get_num_keyvalues(); i++ ) {	// don't loop on the swapped count use the original
        keyValue = dict.get_keyvalues( i );
        WriteString( keyValue->get_key().c_str(), f );
        WriteString( keyValue->get_value().c_str(), f );
    }
}

INF_INLINE void ReadFromFileHandle( inf::Dict& dict, File *f ) {
    int c;
    inf::Str key, val;

    dict.clear();

    f->Read( &c, sizeof( c ) );
    c = inf::little_long( c );
    for ( int i = 0; i < c; i++ ) {
        key = ReadString( f );
        val = ReadString( f );
        dict.set( key, val );
    }
}

#endif // DictUtil_h__